package com.gui.juc.base.thread.method;


import cn.hutool.core.util.RandomUtil;
import com.gui.utils.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.text.DecimalFormat;
import java.util.concurrent.TimeUnit;

@Slf4j
public class InterrupterDemo3 {

    public static void main(String[] args) {

        Thread monitorThread = new Thread(() -> {
            log.debug("start monitor...");
            DecimalFormat df = new DecimalFormat("#.00");
            while (true) {
                if (Thread.currentThread().isInterrupted()){
                    log.debug("不监控了，优雅退出...");
                    break;
                }
                try {
                    TimeUnit.SECONDS.sleep(2);
                    double cpuUsageRate = RandomUtil.randomDouble(1d, 50);
                    log.debug("CPU使用情况：{}%...", df.format(cpuUsageRate));
                } catch (InterruptedException e) {
                    log.error("线程被打断...");
                    Thread.currentThread().interrupt();
                }
            }
        }, "monitor-thread");

        monitorThread.start();

        log.warn("main start...");
        Sleeper.sleepS(15);
        log.warn("main interrupt...");
        monitorThread.interrupt();

    }

}
